<?php 
use Org\Util\Wechat;
/**
 * 通过http get的方式向服务器端请求数据
 * @param string $url 请求链接
 * @return object 
 */
    function httpGet($url){
    	//初始化
		$ch = curl_init();
		//设置选项，包括URL
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 1);

		$session_id = null;
    	$cookie = '';
    	if(myCookie("USER_DATA")!=null){
			$cookie .= myCookie("USER_DATA").';';
		}
    	if(session('JSESSIONID')!=null){
    		$cookie .= session('JSESSIONID').';';
    		\Think\Log::write("mycookie:".$cookie);
		}
		curl_setopt ($ch, CURLOPT_COOKIE , $cookie);
		/*
		if(C('CHINT_AGENT')) {
			$proxy = C('AGENT_URL');
			$proxyport = C('AGENT_PORT');
			curl_setopt($ch, CURLOPT_PROXY, $proxy);
			curl_setopt($ch, CURLOPT_PROXYPORT, $proxyport);
		}
		*/
		//执行并获取HTML文档内容
		$output = curl_exec($ch);
		//释放curl句柄
		curl_close($ch);
		\Think\Log::write('output:'.$output,'INFO');

		preg_match('/Set-Cookie:(.*);/iU',$output,$session_id); //正则匹配

		if($session_id[1]!=null){
			session('JSESSIONID',$session_id[1]);
			$sessions = explode('=', $session_id[1]);
			cookie("JSESSIONID",$sessions[1]);
		}

		$responseBlock = explode("\r\n\r\n",$output);
		$response_body = $responseBlock[count($responseBlock)-1];

		$msg = json_decode($response_body);
		return $msg;
    }
/**
 * 通过http post的方式向服务器端请求数据
 * @param string $url 请求链接
 * @param array $post_data 请求参数数组
 * @return object 
 */
    function httpPost($url,$post_data){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		// post数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// post的变量
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

		$session_id = null;
    	$cookie = null;
    	if(myCookie("USER_DATA")!=null){
			$cookie .= myCookie("USER_DATA").';';
		}
    	if(session('JSESSIONID')!=null){
    		$cookie .= session('JSESSIONID').';';
    		\Think\Log::write("mycookie:".$cookie);
		}
		curl_setopt ($ch, CURLOPT_COOKIE , $cookie);
		
		/*
if(C('CHINT_AGENT')) {
			$proxy = C('AGENT_URL');
			$proxyport = C('AGENT_PORT');
			curl_setopt($ch, CURLOPT_PROXY, $proxy);
			curl_setopt($ch, CURLOPT_PROXYPORT, $proxyport);
		}
*/
		
		$output = curl_exec($ch);
		curl_close($ch);
		\Think\Log::write('output:'.$output,'INFO');

		preg_match('/Set-Cookie:(.*);/iU',$output,$session_id); //正则匹配

		if($session_id[1]!=null){
			session('JSESSIONID',$session_id[1]);
			$sessions = explode('=', $session_id[1]);
			cookie("JSESSIONID",$sessions[1]);
		}

		$responseBlock = explode("\r\n\r\n",$output);
		$response_body = $responseBlock[count($responseBlock)-1];

		\Think\Log::write('body:'.$response_body,'INFO');


		$msg = json_decode($response_body);
		return $msg;
    }

    function myCookie($cookieName,$cookieValue=null){
    	\Think\Log::write('cookieName:'.$cookieName,'INFO');
    	\Think\Log::write('cookieValue:'.$cookieValue,'INFO');
    	$key = "123456789";
    	//$name = \Think\Crypt\Driver\Des::encrypt($cookieName,$key);
    	
    	\Think\Log::write('name:'.$cookieName,'INFO');
    	
    	if($cookieValue==null){
    		//return \Think\Crypt\Driver\Des::decrypt(cookie($cookieName),$key);
    		return cookie($cookieName);
    		
    		// $temp = \Think\Crypt\Driver\Des::decrypt(cookie($cookieName),$key);
    		// return \Think\Crypt\Driver\Base64::decrypt($temp,$key);

    	}else{
    		//$value = \Think\Crypt\Driver\Des::encrypt($cookieValue,$key,60*60*24*365);
    		//\Think\Log::write('value:'.$value,'INFO');

    		//cookie($cookieName,$value);
    		cookie($cookieName,$cookieValue,array('expire'=>60*60*24*365));
    		// $temp = \Think\Crypt\Driver\Des::encrypt($cookieValue,$key,60*60*24*365);
    		// $value = \Think\Crypt\Driver\Base64::encrypt($temp,$key,60*60*24*365);
    		// cookie($cookieName,$value);
    	}
    }

    /**
  * 获取当前URL
  */
  /*
function getSelfUrl() {
	$secure = (isset($_SERVER["HTTPS"]) && ((strcasecmp($_SERVER["HTTPS"], "on") === 0) || ($_SERVER["HTTPS"] == 1))) || (isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && (strcasecmp($_SERVER["HTTP_X_FORWARDED_PROTO"], "https") === 0)); $hostInfo = "";

	if ($secure) {
		$http = "https";
	} else {
		$http = "http";
	}

	if (isset($_SERVER["HTTP_HOST"])) {
		$hostInfo = $http . "://" . $_SERVER["HTTP_HOST"]; 
	} else {
		$hostInfo = $http . "://" . $_SERVER["SERVER_NAME"];

		if ($secure) {
			$port = (isset($_SERVER["SERVER_PORT"]) ? (int) $_SERVER["SERVER_PORT"] : 443); 
		} else {
			$port = (isset($_SERVER["SERVER_PORT"]) ? (int) $_SERVER["SERVER_PORT"] : 80); 
		}

		if ((($port !== 80) && !$secure) || (($port !== 443) && $secure)) { 
			$hostInfo .= ":" . $port; 
		} 
	}
	$requestUri = "";
	if (isset($_SERVER["HTTP_X_REWRITE_URL"])) { 
		$requestUri = $_SERVER["HTTP_X_REWRITE_URL"]; 
	} else if (isset($_SERVER["REQUEST_URI"])) { 
		$requestUri = $_SERVER["REQUEST_URI"];

		if (!empty($_SERVER["HTTP_HOST"])) {
			if (strpos($requestUri, $_SERVER["HTTP_HOST"]) !== false) { 
				$requestUri = preg_replace("/^\w+:\/\/[^\/]+/", "", $requestUri); 
			} 
		} else { 
			$requestUri = preg_replace("/^(http|https):\/\/[^\/]+/i", "", $requestUri); 
		} 
	} else if (isset($_SERVER["ORIG_PATH_INFO"])) { 
		$requestUri = $_SERVER["ORIG_PATH_INFO"];

		if (!empty($_SERVER["QUERY_STRING"])) {
			$requestUri .= "?" . $_SERVER["QUERY_STRING"]; 
		} 
	} else {
		exit("没有获取到当前的url");
	}

	return $hostInfo . $requestUri;
}

*/

/* 
 * author wczmatthew
 * 生成微信JS的签名
 * return array
 */
/*
function getWXJsSign() {
	$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
	$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
	
	$weObj = new \Org\Util\Wechat();
	$signPackage = $weObj->getJsSign($url);
	return $signPackage;
}
*/
/* 
 * author@wczmatthew
 * 获取微信模板消息 内容 里的关键词，返回数组
 * @param 模板消息内容content字段
 * return array
 */
function getTplContentKeywords($content) {
	$keywordArrTmp = explode("\n", $content);
	// 去掉收尾两个元素：first 和 remark
	array_shift($keywordArrTmp);
	array_pop($keywordArrTmp);
	
	$keywordArr = array();
	$count = 0;
	// 去掉空值
	for($i=0; $i<count($keywordArrTmp); $i++) {
		if(!empty($keywordArrTmp[$i])) {
			$keywordLen = strlen($keywordArrTmp[$i]);			// 记录字符串长度
			$dKuohaoIndex = strpos($keywordArrTmp[$i], "{{");	// 记录{{的索引位置
			$value = substr($keywordArrTmp[$i], 0, $dKuohaoIndex);// 截取中文
			
			$keyLen = $keywordLen - $dKuohaoIndex;
			$key = substr($keywordArrTmp[$i], $dKuohaoIndex+2, $keyLen-9);// 截取英文，减去9，因为{{.DATA}}合计9
			
			$keywordArr[$count++] = array($key => $value);		// 加入数组
		}
	}
	return $keywordArr;
}

/* 
 * author@wczmatthew
 * ***** 还需优化 *****
 * 只适用于keyword1-n情况，但是很多模板消息存在自定义keyword
 * @param 模板消息内容content字段
 * return array
 */
function getTplContentKeywords1($content) {
	// DATA计数，表明有几个关键词（包含first 和 remark）
	$data_count = substr_count($content,"DATA");
	// 替换first 和 remark，方便后面处理
	$content1 = str_replace("first","keyword0",$content);
	$content2 = str_replace("remark","keyword".($data_count-1),$content1);
	
	// 去掉keyword0和最后一个keywordn，方便字符串分离
	$content2 = str_replace("{{keyword0.DATA}}","",$content2);
	$content2 = str_replace("{{keyword".($data_count - 1).".DATA}}","",$content2);
	// 去掉字符串中的换行符回车
	$content2 = str_replace("\n", "", $content2);
	// 替换keyword1 - (n-1),全部变成keyword.DATA，方便后面字符串分离
	for($i=1;$i<$data_count-1;$i++) {
		$content2 = str_replace("keyword".$i,"keyword",$content2);
	}
	
	$keywordArr = explode("{{keyword.DATA}}",$content2);
	// 去掉最后一个空值
	array_pop($keywordArr);
	
	return $keywordArr;
}

function getComboPackname($id) {
	$cbpnames = C('cbp_names_arr');
	return $cbpnames[$id];
}

function getCollocation($json_collocation) {
	
	return json_decode($json_collocation);
}
function httpGetUsercenter($url){
	//初始化
	$ch = curl_init();
	//设置选项，包括URL
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 1);

	//执行并获取HTML文档内容
	$output = curl_exec($ch);
	//释放curl句柄
	curl_close($ch);
	\Think\Log::write('output => '.$output,'INFO');
	$responseBlock = explode("\r\n\r\n",$output);
	$response_body = $responseBlock[count($responseBlock)-1];
	
	$msg = json_decode($response_body);
	return $msg;
}

/*
 * 	检查权限
 *	为方便统一操作, 规定订单号id名称为orderid
 *  $data 为数据库操作的data
 */ 
function checkUserPrivilege($openid = null, $data=null) {
    if(empty($openid)) {$openid = session('openid');}
	
	// 获取用户权限,将权限名放入数组
	$url = 'http://'.$_SERVER['HTTP_HOST'].'/usercenter/index.php/User/Index/getUserRoleFunc?loginUserId='.$openid;
	$userPrivilege = httpGetUsercenter($url);
	$userPrivilegeNames = array();
	foreach($userPrivilege as $pri) {
		$userPrivilegeNames[] = $pri->menuname;
	}
	$userPrivilegeNames = implode($userPrivilegeNames);
	// 如果操作为修改订单 | 提交订单
	if(ACTION_NAME == 'submitOrder' || ACTION_NAME == 'editAutoOrder') {
		// QueryOrderAll | QueryOrderSelf
		if(strstr($userPrivilegeNames,'QueryOrderAll')) {
			return array(0, 'ok');
		} elseif (strstr($userPrivilegeName, 'QueryOrderSelf')) {
			$orderid = I('orderid');
			// 非空且不是新建订单，新建订单orderid为0
			if($orderid) {
				$condition = array();
				$condition['id'] = $orderid;
				$condition['openid'] = $openid;
				$order = M('order')->where($condition)->find();
				if($order) {
					return array(0, 'ok');
				} else {
					return array(1, '您无权修改此订单!');
				}
			} else {
				return array(0, 'ok');;
			}
		}
	} elseif(ACTION_NAME == 'deliverOrder'){
		if(strstr($userPrivilegeNames, 'deliverOrderAll')) {
			return array(0, 'ok');
		} 
		return array(1, '您无权浏览配送列表!');
	} else {
		return array(0, 'ok');
	}
}

/*
 *	param(isReturn：是否返回结果) 针对自动发送 和 手动重新发送
 */
function pushWXTplMsg($openid, $nickname, $period, $isReturn=false) {
	$user = M('wxuser')->where(array('openid' => $openid))->find();
	if(C('showSysMsg')) {
		$first = "尊敬的".$nickname."，您有新一期套餐点菜开始啦！(".C('sysMsgTitle').")";
	} else {
		$first = "尊敬的".$nickname."，您有新一期套餐点菜开始啦！";
	}
	$keyword1 = $period['ppname']."套餐点菜";
	$startMonth = (int)date("m", $period['fromtime']);
	$startDay = (int)date("d", $period['fromtime']);
	$startTime = date("H:i", $period['fromtime']);
	$endMonth = (int)date("m", $period['endtime']);
	$endDay = (int)date("d", $period['endtime']);
	$endTime = date("H:i", $period['endtime']);
	$keyword2 = $startMonth.'月'.$startDay.'日 '.$startTime . '-' . $endMonth . '月'.$endDay.'日 '.$endTime;
	$remark = "九亩倾心为您打造有机餐桌。";
	$data = array("touser"=>$user['openid'],
				"template_id"=>"msCBRvXMNr6YR2_0FQVrqvH0B8PSH7O9ijS5DNBcAXM",
				"url"=> C('site_url').U('Wap/OrderFood/index'),
				"topcolor"=>"#FF0000",
				"data"=> array( "first"=>array("value"=>$first, "color"=>"#173177"), 
							"keyword1" =>array("value"=>$keyword1, "color"=>"#173177"),
							"keyword2" =>array("value"=>$keyword2, "color"=>"#173177"),
							"remark"   =>array("value"=>$remark, "color"=>"#173177"),
				)
	);
	$weObj = new Wechat();
	$msg_result = $weObj->sendTemplateMessage($data);
	// 更新用户模板消息的状态
	$msg_data = array(
		"msgid" 	=> $msg_result['msgid'],
		"errcode"	=> $msg_result['errcode'],
		"opid"		=> $period['periodid'],
	);
	\Think\Log::write("向".$nickname."(".$openid.")发送");
	\Think\Log::write("msg_result => ". dump($msg_result, false));
	
	if($isReturn) {
		if($msg_result['errcode'] == 0 && !empty($msg_result['msgid'])) {
			// 如果正确发送成功，更新字段
			M('wxuser')->where(array("openid" => $openid))->save($msg_data);
			return array('result_code' => 1, 'result_msg' => '消息发送成功,系统将自动为您刷新送达结果状态！');
		} else {
			return array('result_code' => 0, 'result_msg' => '消息发送失败!');
		}
	} else {
		$res = M('wxuser')->where(array("openid" => $openid))->save($msg_data);
		return array($res, $errcode, $msgid);
	}
}
 ?>
